﻿using Microsoft.Win32;
using OxyPlotTester.ViewModels;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using WPFTemplateLib.WpfHelpers;

namespace WPFTemplate
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = new MainWindowViewModel();
        }

        private void ExportPicBtn_OnClick(object sender, RoutedEventArgs e)
        {
            ExportPicture(Plot);
        }

        /// <summary>
        /// 导出图片
        /// </summary>
        /// <param name="element">xaml里面的某个可视化元素对象</param>
        private void ExportPicture(FrameworkElement element)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "PNG文件(*.png)|*.png|JPG文件(*.jpg)|*.jpg|BMP文件(*.bmp)|*.bmp|GIF文件(*.gif)|*.gif|TIF文件(*.tif)|*.tif"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                string dir = System.IO.Path.GetDirectoryName(saveFileDialog.FileName);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                string filePath = saveFileDialog.FileName;
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                bool success = ExportPicHelper.SaveToImage(element, filePath, out string errorMsg);
                if (success)
                {
                    MessageBox.Show($"导出成功");
                }
                else
                {
                    MessageBox.Show($"导出失败 {errorMsg}");
                }
            }
        }
    }
}
